<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\UserMovie;
use Illuminate\Http\Request;

class MovieController extends Controller
{
    const USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
        Chrome/8.0.552.224 Safari/534.10";
    const CHECK_URL_VALID = "/(youku\.com|tudou\.com|ku6\.com|56\.com|letv\.com|video\.sina\.com\.cn|(my\.)?tv\.sohu\.com|v\.qq\.com)/";

    public function index(Request $request)
    {

//        $url = "https://m.youku.com/video/id_XMzg1NTE0NzM1Mg==.html?spm=a2h0j.11185381.listitem_page1.5!5~A&source";
//        $url = "https://m.v.qq.com/x/cover/s/su8uft5oqt0m8nz.html?vid=m0738lsb8u5&ptag=";
//        $url = "https://m.tv.sohu.com/v106325717.shtml?site=2&channeled=1210040003";

        $url = $request->input('url');
        $data = self::parse($url);


//        echo '<iframe frameborder="0" height="60%" width="100%" allowfullscreen="" src="' . $data['swf'] . '"></iframe>';
//        exit;
        return $this->renderJson($data);
    }

    private static function parse($url = '', $createObject = true)
    {
        $lowerurl = strtolower($url);
        preg_match(self::CHECK_URL_VALID, $lowerurl, $matches);
        if (!$matches) return false;

        switch ($matches[1]) {
            case 'youku.com':
                $data = self::_parseYouku($url);
                break;
            case 'tudou.com':
                $data = self::_parseTudou($url);
                break;
            case 'ku6.com':
                $data = self::_parseKu6($url);
                break;
            case '56.com':
                $data = self::_parse56($url);
                break;
            case 'letv.com':
                $data = self::_parseLetv($url);
                break;
            case 'video.sina.com.cn':
                $data = self::_parseSina($url);
                break;
            case 'my.tv.sohu.com':
            case 'tv.sohu.com':
            case 'sohu.com':
                $data = self::_parseSohu($url);
                break;
            case 'v.qq.com':
                $data = self::_parseQq($url);
                break;
            default:
                $data = false;
        }

        return $data;
    }

    /**
     * 优酷网
     * http://v.youku.com/v_show/id_XMjI4MDM4NDc2.html
     * http://player.youku.com/player.php/sid/XMjU0NjI2Njg4/v.swf
     */
    private static function _parseYouku($url)
    {
        preg_match("#id\_(\w+)#", $url, $matches);

        if (empty($matches)) {
            if (!$matches) return false;
        }

        $showdata = self::_cget($url);
        preg_match("/<title>(.*)<\/title>/", $showdata, $title);
        preg_match('/<meta itemprop="image" content="(.*)"\/>/', $showdata, $content);
        preg_match('/<meta property="og:description" content="(.*)?"\/>/', $showdata, $des);

        if (!empty($title) && !empty($content)) {
            $data['img'] = $content[1];
            $data['title'] = $title[1];
            $data['des'] = $des[1];
            $data['swf'] = "http://player.youku.com/embed/{$matches[1]}==";
            $data['url'] = $url;
            return $data;
        } else {
            return false;
        }
    }

    /**
     * 腾讯视频
     * http://v.qq.com/cover/o/o9tab7nuu0q3esh.html?vid=97abu74o4w3_0
     * http://v.qq.com/play/97abu74o4w3.html
     * http://v.qq.com/cover/d/dtdqyd8g7xvoj0o.html
     * http://v.qq.com/cover/d/dtdqyd8g7xvoj0o/9SfqULsrtSb.html
     * http://imgcache.qq.com/tencentvideo_v1/player/TencentPlayer.swf?_v=20110829&vid=97abu74o4w3&autoplay=1&list=2&showcfg=1&tpid=23&title=%E7%AC%AC%E4%B8%80%E7%8E%B0%E5%9C%BA&adplay=1&cid=o9tab7nuu0q3esh
     */
    private static function _parseQq($url)
    {

        preg_match("/vid=([^\_]+)/", $url, $matches);
        if (empty($matches)) {
            return false;
        }
        $vid = $matches[1];
        $swf = explode("&", $vid);

        $showdata = self::_fget($url);

        preg_match("/<title>(.*)<\/title>/", $showdata, $title);
        preg_match("/<div class=\"video_tit U_color_a\">(.*)<\/div>/", $showdata, $title);
        preg_match('/<meta name="description" content="(.*)" \/>/', $showdata, $des);

        if (empty($title)) {
            return false;
        }
        $data['img'] = "http://puui.qpic.cn/qqvideo_ori/0/" . $swf[0] . "_496_280/0";
        $data['title'] = $title[1];
        $data['des'] = $des[1];
        $data['swf'] = "https://v.qq.com/iframe/player.html?vid=" . $swf[0] . "&tiny=0&auto=0";
        $data['url'] = $url;
        return $data;
    }

    // 搜狐TV
    private static function _parseSohu($url)
    {
        preg_match_all('/om\/v(\d+)\.shtml/', $url, $matches);

        $showdata = self::_fget($url);

        preg_match("/<title>(.*)<\/title>/", $showdata, $title);
//        preg_match_all('/<meta name="description" content="(.*)/', $showdata, $des);
//var_dump($des);exit;

        $data['swf'] = "https://tv.sohu.com/upload/static/share/share_play.html#" . $matches[1][0] . "___9001_";
        $data['img'] = "";
        $data['title'] = $title[1];
        $data['des'] = $title[1];
        $data['url'] = $url;

        return $data;
    }

    /*
     * 通过 curl 获取内容
     */
    private static function _cget($url = '', $user_agent = '')
    {

        if (!$url) return;

        $user_agent = $user_agent ? $user_agent : self::USER_AGENT;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        if (strlen($user_agent)) curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);

        ob_start();
        curl_exec($ch);
        $html = ob_get_contents();
        ob_end_clean();

        if (curl_errno($ch)) {
            curl_close($ch);
            return false;
        }
        curl_close($ch);
        if (!is_string($html) || !strlen($html)) {
            return false;
        }
        return $html;
        // 判断是否gzip压缩
        if ($dehtml = self::_gzdecode($html))
            return $dehtml;
        else
            return $html;
    }

    /*
 * 通过 file_get_contents 获取内容
 */
    private static function _fget($url = '')
    {
        if (!$url) return false;
        $html = file_get_contents($url);
        // 判断是否gzip压缩
        if ($dehtml = self::_gzdecode($html)) {
            return $dehtml;
        } else {
            return $html;
        }
    }

    private static function _gzdecode($data)
    {
        $len = strlen($data);
        if ($len < 18 || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
            return null; // Not GZIP format (See RFC 1952)
        }
        $method = ord(substr($data, 2, 1)); // Compression method
        $flags = ord(substr($data, 3, 1)); // Flags
        if ($flags & 31 != $flags) {
            // Reserved bits are set -- NOT ALLOWED by RFC 1952
            return null;
        }
        // NOTE: $mtime may be negative (PHP integer limitations)
        $mtime = unpack("V", substr($data, 4, 4));
        $mtime = $mtime [1];
        $xfl = substr($data, 8, 1);
        $os = substr($data, 8, 1);
        $headerlen = 10;
        $extralen = 0;
        $extra = "";
        if ($flags & 4) {
            // 2-byte length prefixed EXTRA data in header
            if ($len - $headerlen - 2 < 8) {
                return false; // Invalid format
            }
            $extralen = unpack("v", substr($data, 8, 2));
            $extralen = $extralen [1];
            if ($len - $headerlen - 2 - $extralen < 8) {
                return false; // Invalid format
            }
            $extra = substr($data, 10, $extralen);
            $headerlen += 2 + $extralen;
        }

        $filenamelen = 0;
        $filename = "";
        if ($flags & 8) {
            // C-style string file NAME data in header
            if ($len - $headerlen - 1 < 8) {
                return false; // Invalid format
            }
            $filenamelen = strpos(substr($data, 8 + $extralen), chr(0));
            if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) {
                return false; // Invalid format
            }
            $filename = substr($data, $headerlen, $filenamelen);
            $headerlen += $filenamelen + 1;
        }

        $commentlen = 0;
        $comment = "";
        if ($flags & 16) {
            // C-style string COMMENT data in header
            if ($len - $headerlen - 1 < 8) {
                return false; // Invalid format
            }
            $commentlen = strpos(substr($data, 8 + $extralen + $filenamelen), chr(0));
            if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) {
                return false; // Invalid header format
            }
            $comment = substr($data, $headerlen, $commentlen);
            $headerlen += $commentlen + 1;
        }

        $headercrc = "";
        if ($flags & 1) {
            // 2-bytes (lowest order) of CRC32 on header present
            if ($len - $headerlen - 2 < 8) {
                return false; // Invalid format
            }
            $calccrc = crc32(substr($data, 0, $headerlen)) & 0xffff;
            $headercrc = unpack("v", substr($data, $headerlen, 2));
            $headercrc = $headercrc [1];
            if ($headercrc != $calccrc) {
                return false; // Bad header CRC
            }
            $headerlen += 2;
        }

        // GZIP FOOTER - These be negative due to PHP's limitations
        $datacrc = unpack("V", substr($data, -8, 4));
        $datacrc = $datacrc [1];
        $isize = unpack("V", substr($data, -4));
        $isize = $isize [1];

        // Perform the decompression:
        $bodylen = $len - $headerlen - 8;
        if ($bodylen < 1) {
            // This should never happen - IMPLEMENTATION BUG!
            return null;
        }
        $body = substr($data, $headerlen, $bodylen);
        $data = "";
        if ($bodylen > 0) {
            switch ($method) {
                case 8 :
                    // Currently the only supported compression method:
                    $data = gzinflate($body);
                    break;
                default :
                    // Unknown compression method
                    return false;
            }
        } else {
            //...
        }

        if ($isize != strlen($data) || crc32($data) != $datacrc) {
            // Bad format!  Length or CRC doesn't match!
            return false;
        }
        return $data;
    }

    // 编辑视频
    public function edit(Request $request)
    {
        $user_id = $request->user()->id;
        $id = $request->input('id');
        if (empty($id)) {
            return $this->fail('id不能为空');
        }
        $title = $request->input('title');
        $description = $request->input('description');
        $img = $request->input('img');
        $swf = $request->input('swf');
        $url = $request->input('url');
        $info = UserMovie::where('id', $id)->where('user_id', $user_id)->first();
        if (empty($info)) {
            return $this->fail('没有该视频');
        }

        $info->title = $title;
        $info->description = $description;
        $info->img = $img;
        $info->swf = $swf;
        $info->url = $url;
        $t = $info->save();
        if ($t) {
            return $this->success("编辑成功");
        } else {
            return $this->fail('编辑出错');
        }
    }

    // 查看视频
    public function one(Request $request)
    {
        $user_id = $request->user()->id;
        $id = $request->input('id');
        $info = UserMovie::where('id', $id)->where('user_id', $user_id)->first();

        if (empty($info)) {
            return $this->renderJson();
        }
        return $this->renderJson($info);
    }

    public function search(Request $request)
    {
        $user_id = $request->user()->id;
        $search = $request->input('search');
        $info = UserMovie::where('title', 'like' ,"%". $search. "%")->where('user_id', $user_id)->orderByDesc('created_at')->paginate(request('limit'))->toArray();

        if (empty($info)) {
            return $this->renderJson();
        }
        return $this->renderJson($info);
    }

    // 添加视频
    public function add(Request $request)
    {
        $user_id = $request->user()->id;
        $title = $request->input('title');
        $description = $request->input('description');
        $img = $request->input('img');
        $swf = $request->input('swf');
        $url = $request->input('url');
        $userMovie = new UserMovie();

        $userMovie->title = $title;
        $userMovie->user_id = $user_id;
        $userMovie->description = $description;
        $userMovie->img = $img;
        $userMovie->swf = $swf;
        $userMovie->url = $url;
        $t = $userMovie->save();
        if ($t) {
            return $this->success("添加成功");
        } else {
            return $this->fail('添加出错');
        }
    }

    // 删除视频
    public function delete(Request $request)
    {
        $user_id = $request->user()->id;
        $id = $request->input('id');
        $t = UserMovie::where('id', $id)->where('user_id', $user_id)->delete();
        if ($t) {
            return $this->success("删除成功");
        } else {
            return $this->fail('删除出错');
        }
    }

    // 列表视频
    public function lists(Request $request)
    {
        $user_id = $request->user()->id;
        $info = UserMovie::where('user_id', $user_id)->orderByDesc('created_at')->paginate(request('limit'))->toArray();
        if (empty($info)) {
            return $this->renderJson();
        }

        return $this->renderJson($info);
    }
}
